package cn.hdu.community.util;

import cn.hdu.community.service.UserService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;

/**
 * @Author zhangxin
 * @Date 2022/4/4
 */

@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    UserService userService;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //拦截器只是负责把有请求头中包含token的令牌进行一个解析验证。
        String header = request.getHeader("Authorization");

        if (header != null && !"".equals(header)) {
            //如果有包含有Authorization头信息，就对其进行解析
            if (header.startsWith("Bearer ")) {
                //得到token
                String token = header.substring(7);
                //对令牌进行验证
                Claims claims = JwtTokenUtil.parseJWT(token);
                String roles = (String) claims.get("roles");
                Integer userId = Integer.valueOf(claims.getSubject());
                if (roles != null && roles.equals("admin")) {
                    request.setAttribute("claims_admin", token);
                    request.setAttribute("userId", userId);
                    userService.insertUserActivityTime(userId, LocalDate.now());
                    return true;
                }
                if (roles != null && roles.equals("user")) {
                    request.setAttribute("claims_user", token);
                    request.setAttribute("userId", userId);
                    userService.insertUserActivityTime(userId, LocalDate.now());
                    return true;
                }
            }
        }
        return false;
    }
}
